<!-- 使用 type="home" 属性设置首页，其他页面不需要设置，默认为page；推荐使用json5，更强大，且允许注释 -->
<route lang="json5" type="page">
{
  layout: 'default',
  style: {
    navigationStyle: 'custom',
    navigationBarTitleText: '新增持有',
  },
}
</route>
<template>
  <PageLayout :navbarShow="true" navTitle="新增持有">
    <scroll-view class="wrap" scroll-y>
      <view class="box">
        <view style="margin-bottom: 20rpx">新增持仓</view>
        <wd-picker
          title="点击确定即分组"
          :columns="groupList"
          v-model="addObj.groupName"
          use-default-slot
        >
          <view class="box-row" style="margin-bottom: 16rpx">
            <view class="box-row-name">所属组合</view>
            <view class="box-row-data">{{ addObj.groupName || '默认' }}</view>
          </view>
        </wd-picker>
        <view class="box-row" style="margin-bottom: 16rpx" @click="onClickNameOrCode()">
          <view class="box-row-name">基金名称</view>
          <view class="box-row-data">
            {{ addObj.fundName || '请输入名称（必填）' }}
          </view>
        </view>
        <view class="box-row" style="margin-bottom: 16rpx">
          <view class="box-row-name">持仓数量</view>
          <view class="box-row-data" @click="onClickNum('holdNum')">
            {{ addObj.holdNum || '请输入持仓数量（必填）' }}
          </view>
        </view>
        <view class="box-row">
          <view class="box-row-name">持仓盈亏</view>
          <view class="box-row-data" @click="onClickNum('money')">
            {{ addObj.money || '请输入盈亏金额（必填）' }}
          </view>
        </view>

        <wd-number-keyboard
          v-model:visible="visibleKeyoard"
          :extra-key="['清空', '.']"
          close-text="完成"
          mode="custom"
          @input="onInput"
          @delete="onDelete"
        ></wd-number-keyboard>
      </view>

      <view
        style="
          width: 95%;
          margin: 0 auto;
          padding: 20rpx;
          background-color: #fff;
          border-radius: 20rpx;
        "
      >
        <view>新增列表</view>
        <view style="color: #8a8a8a; margin-top: 10rpx; font-size: 24rpx">每次可添加多个持仓</view>
        <view
          v-if="addList.length > 0"
          style="background-color: #f6f8fb; padding: 20rpx; margin-top: 20rpx; border-radius: 10rpx"
        >
          <view
            v-for="i in addList"
            :key="i"
            style="border-bottom: 1px solid #f2f2f2; padding: 10rpx 0rpx"
          >
            <view style="display: flex">
              <!-- <view>图表</view> -->
              <view>{{ i.fundName }}</view>
            </view>
            <view style="display: flex; font-size: 20rpx; color: #515151; margin-top: 10rpx">
              <view>{{ i.groupName || '默认' }}</view>
              <view style="margin-left: 10rpx">{{ i.holdNum || '--' }}份</view>
              <view style="margin-left: 10rpx">{{ i.money || '--' }}元</view>
            </view>
          </view>
        </view>
        <!--空数据提示-->
        <wd-status-tip image="../../static/content.png" tip="暂未添加持有基金" v-else />
      </view>
    </scroll-view>
    <view
      style="display: flex; background-color: #fff; padding: 30rpx 0rpx; justify-content: center"
    >
      <view class="btn-add" @click="onClickJxAdd" style="background-color: #ecf1fc; color: #5380f6">
        继续插入
      </view>
      <view class="btn-add" @click="onClickHold">立即提交</view>
    </view>

    <!--弹窗-->
    <wd-popup custom-style="width: 640rpx;" v-model="show" position="right" @close="handleClose">
      <!--搜索栏-->
      <wd-search v-model="searchStr" @change="change" @cancel="cancel" />
      <!--空数据提示-->
      <wd-status-tip
        image="../../static/content.png"
        tip="暂无搜索数据"
        v-if="searchList.length == 0 && !showLoadingView"
      />
      <!--骨架屏-->
      <view v-else-if="showLoadingView">
        <wd-skeleton theme="paragraph" style="margin-bottom: 10rpx" />
        <wd-skeleton theme="paragraph" style="margin-bottom: 10rpx" />
        <wd-skeleton theme="paragraph" style="margin-bottom: 10rpx" />
      </view>
      <!--列表-->
      <view
        v-else-if="!showLoadingView && searchList.length > 0"
        v-for="i in searchList"
        :key="i"
        class="item"
        @click="onClickItem(i)"
      >
        <view style="margin-bottom: 16rpx">{{ i.name }}</view>
        <view style="font-size: 20rpx">
          <wd-tag color="#0083ff" bg-color="#d0e8ff" style="margin-right: 4px">
            {{ i.code }}
          </wd-tag>
          <wd-tag color="#0083ff" bg-color="#d0e8ff" style="margin-right: 4px">
            {{ i.type }}
          </wd-tag>
          <wd-tag color="#0083ff" bg-color="#d0e8ff" style="margin-right: 4px">
            {{ i.risk }}
          </wd-tag>
          <wd-tag color="#0083ff" bg-color="#d0e8ff" style="margin-right: 4px">
            近1年：
            <text :style="{ color: i.syl_1n != null && i.syl_1n > 0 ? 'red' : 'green' }">
              {{
                i.syl_1n == null
                  ? '--'
                  : i.syl_1n > 0
                    ? '+' + i.syl_1n.toFixed(2)
                    : i.syl_1n.toFixed(2)
              }}{{ i.syl_1n == null ? '' : '%' }}
            </text>
          </wd-tag>
        </view>
      </view>
      <!--查看更多-->
      <view
        v-if="totalPages > pageNo && searchList.length > 0"
        style="text-align: center; padding: 20rpx 0px"
        @click="onClickMore"
      >
        查看更多
      </view>
    </wd-popup>
  </PageLayout>
</template>

<script lang="ts" setup>
import { ref } from 'vue'
import { http } from '@/utils/http'
import { useToast } from 'wot-design-uni'
import { isNumber } from '@/common/is'

defineOptions({
  name: 'addChoose',
  options: {
    styleIsolation: 'shared',
  },
})
// 弹窗显示
const show = ref(false)
// 点击的item
const itemId = ref(0)
// 搜索条件
const searchStr = ref('')
// 每页显示数量
const pageSize = ref(10)
// 当前页码
const pageNo = ref(1)
// 查询列表
const searchList = ref([])
// 总页码
const totalPages = ref(0)
// 骨架屏
const showLoadingView = ref(false)
// 添加列表
const addList = ref([])
// 分组列表
const groupList = ref([])
// 原分组
const initGroup = ref([])
// 对象
const addObj = ref<any>({})
// 提示
const toast = useToast()
// 是否显示键盘
const visibleKeyoard = ref(false)
// key
const numKey = ref('')

// 加载分组列表
const loadGroupList = () => {
  http.get('/sys/fund/hold/group/list').then((res: any) => {
    if (res.success) {
      // 结果集
      const result = res.result
      // 赋值初始数组
      initGroup.value = result
      // 数据
      const data = ['默认']
      // 遍历
      result.forEach((i) => {
        data.push(i.name)
      })
      groupList.value = data
    }
  })
}
// 点击显示数字键盘
const onClickNum = (key) => {
  visibleKeyoard.value = true
  numKey.value = key
}
// 输入
const onInput = (value) => {
  console.log(value)
  if (value === '清空') {
    addObj.value[numKey.value] = ''
  } else {
    // 非清空操作
    const data = addObj.value[numKey.value]
    // 结果数据
    addObj.value[numKey.value] = (data || '') + '' + value
  }
}
// 输入
const onDelete = () => {
  const data = addObj.value[numKey.value]
  addObj.value[numKey.value] =
    data === undefined || data === '' ? '' : data.substring(0, data.length - 1)
}
// 点击跳转到添加页面
const onClickNameOrCode = () => {
  show.value = true
  itemId.value = addObj.value.itemId
}
// 关闭弹窗
const handleClose = () => {
  show.value = false
}
// 点击继续添加
const onClickJxAdd = () => {
  if (addObj.value.fundName === undefined) {
    toast.show('请选择基金')
    return
  } else if (addObj.value.holdNum === undefined || !Number(addObj.value.holdNum)) {
    toast.show('请输入有效持仓数量')
    return
  } else if (addObj.value.money === undefined || !Number(addObj.value.money)) {
    toast.show('请输入有效持仓盈亏金额')
    return
  }
  // 插入数据
  addList.value.push(addObj.value)
  // 插入完成则清空数据
  addObj.value = {}
}
// 点击新增持有
const onClickHold = () => {
  if (addList.value.length === 0) {
    onClickJxAdd()
  }
  // 处理数据
  addList.value.forEach((item) => {
    if (item.groupName !== '默认') {
      for (let i = 0; i < groupList.value.length; i++) {
        const data = groupList.value[i]
        if (data === item.groupName && i !== 0) {
          item.groupId = initGroup.value[i - 1].id
        }
      }
    } else {
      item.groupId = ''
    }
  })
  // console.log(addList.value)
  http.post('/sys/fund/hold/add', addList.value).then((res: any) => {
    if (res.success) {
      // initData()
      toast.show('保存成功')
      // 清空数据
      addList.value = []
    }
  })
}
// 加载搜索的内容
const loadSearchList = () => {
  showLoadingView.value = true
  http
    .get('/sys/fund/library/page', {
      name: searchStr.value,
      pageNo: pageNo.value,
      pageSize: pageSize.value,
    })
    .then((res: any) => {
      if (res.success) {
        // 结果集
        const result = res.result
        // 列表
        const records = result.records
        // 设置搜索结果
        if (pageNo.value === 1) {
          searchList.value = records
        } else {
          records.forEach((item) => {
            searchList.value.push(item)
          })
        }
        // 设置总页码
        totalPages.value = result.pages
        // 隐藏骨架屏
        showLoadingView.value = false
      }
    })
}

// 点击查看更多
const onClickMore = () => {
  if (pageNo.value < totalPages.value) {
    pageNo.value += 1
    loadSearchList()
  }
}

// 点击取消
const cancel = () => {
  searchStr.value = ''
  searchList.value = []
  show.value = false
}

// 点击列表
const onClickItem = (data) => {
  // 相当于点击取消
  cancel()
  // 基金ID
  addObj.value.fundId = data.id
  // 基金名称
  addObj.value.fundName = data.name
}

// 搜索条件改变
const change = () => {
  if (searchStr.value.length > 0) {
    // 内容清空
    searchList.value = []
    // 显示搜索条件
    // showList.value = true
    // 开始搜索
    loadSearchList()
  } else {
    // 不显示搜索条件
    // showList.value = false
    // 数据清空
    searchList.value = []
  }
}

// 数据初始化
const initData = () => {
  // 初始化数据
  // addList.value = [{ fundId: '', fundName: '', groupId: '', groupName: '默认', itemId: 0 }]
}

onLoad(() => {
  initData()
  loadGroupList()
})
</script>

<style lang="scss" scoped>
.wrap {
  background: linear-gradient(to bottom, #daf0fe, #f9fbfb);
  padding: 20rpx;
  .box {
    width: 95%;
    margin: 20rpx auto;
    background-color: #fff;
    padding: 20rpx;
    border-radius: 20rpx;
    .box-row {
      display: flex;
      padding: 10rpx 20rpx;
      border-radius: 10rpx;
      color: #585757;
      font-size: 24rpx;
      .box-row-name {
        width: 60px;
        margin-right: 20px;
      }
    }
  }
  .btn {
    width: 95%;
    margin: 20rpx auto;
    padding: 20rpx;
    text-align: center;
    border-radius: 30rpx;
    background-color: #3b82ec;
    color: #fff;
  }
}
.item {
  border-bottom: 1px solid #f2f2f2;
  padding: 20rpx;
}
.btn-add {
  width: 40%;
  margin: 0rpx 20rpx;
  padding: 20rpx;
  text-align: center;
  border-radius: 25rpx;
  background-color: #3b82ec;
  color: #fff;
}
</style>
